package com.example.SpringMVC.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    @ResponseBody              //表示当前方法或者类返回的是数据而不是页面
    public Object hello(){
        return "helloworld";
    }

    @Value("${upload.path}")
    private String uploadPath;

    @RequestMapping("/file")
    public String upload(@RequestPart("myFile") MultipartFile file) throws IOException {
        //1.上传文件目录
        String basePath =uploadPath;
        //2.生成动态文件名（包含后缀）
        String fileName = UUID.randomUUID() +(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")));
        System.out.println(basePath+fileName);
        //3.保存文件
        file.transferTo(new File(basePath+fileName));
        return "上传成功";
    }

}
